const express = require('express');
const router = express.Router();
const db = require('../utils/database');

/**
 * Record an anonymous visit
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
router.post('/record', (req, res) => {
  try {
    const { fingerprint, pageUrl } = req.body;

    if (!fingerprint || !pageUrl) {
      return res.status(400).json({ 
        success: false, 
        message: 'Missing required fields: fingerprint and pageUrl' 
      });
    }

    // Check if anonymous user exists, if not create one
    db.get(`SELECT id FROM anonymous_users WHERE fingerprint = ?`, [fingerprint], (err, row) => {
      if (err) {
        console.error('Error checking anonymous user:', err);
        return res.status(500).json({ 
          success: false, 
          message: 'Internal server error' 
        });
      }

      if (row) {
        // User exists, record visit
        const anonymousUserId = row.id;
        db.run(`INSERT INTO visits (anonymous_user_id, page_url) VALUES (?, ?)`, 
          [anonymousUserId, pageUrl], 
          function(err) {
            if (err) {
              console.error('Error recording visit:', err);
              return res.status(500).json({ 
                success: false, 
                message: 'Internal server error' 
              });
            }
            
            res.json({ 
              success: true, 
              message: 'Visit recorded successfully',
              visitId: this.lastID
            });
          }
        );
      } else {
        // Create new anonymous user and record visit
        db.run(`INSERT INTO anonymous_users (fingerprint) VALUES (?)`, 
          [fingerprint], 
          function(err) {
            if (err) {
              console.error('Error creating anonymous user:', err);
              return res.status(500).json({ 
                success: false, 
                message: 'Internal server error' 
              });
            }
            
            const anonymousUserId = this.lastID;
            db.run(`INSERT INTO visits (anonymous_user_id, page_url) VALUES (?, ?)`, 
              [anonymousUserId, pageUrl], 
              function(err) {
                if (err) {
                  console.error('Error recording visit:', err);
                  return res.status(500).json({ 
                    success: false, 
                    message: 'Internal server error' 
                  });
                }
                
                res.json({ 
                  success: true, 
                  message: 'New anonymous user created and visit recorded',
                  userId: anonymousUserId,
                  visitId: this.lastID
                });
              }
            );
          }
        );
      }
    });
  } catch (error) {
    console.error('Unexpected error:', error);
    res.status(500).json({ 
      success: false, 
      message: 'Internal server error' 
    });
  }
});

/**
 * Get all anonymous visits with optional filtering
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
router.get('/', (req, res) => {
  try {
    const { limit = 50, offset = 0, startDate, endDate } = req.query;
    
    let sql = `
      SELECT v.id, v.page_url, v.visit_time, au.fingerprint
      FROM visits v
      JOIN anonymous_users au ON v.anonymous_user_id = au.id
    `;
    
    let countSql = `
      SELECT COUNT(*) as count
      FROM visits v
      JOIN anonymous_users au ON v.anonymous_user_id = au.id
    `;
    
    const params = [];
    
    if (startDate || endDate) {
      sql += ' WHERE ';
      countSql += ' WHERE ';
      const conditions = [];
      
      if (startDate) {
        conditions.push('v.visit_time >= ?');
        params.push(startDate);
      }
      
      if (endDate) {
        conditions.push('v.visit_time <= ?');
        params.push(endDate);
      }
      
      sql += conditions.join(' AND ');
      countSql += conditions.join(' AND ');
    }
    
    // Add order and limit for the main query
    sql += ' ORDER BY v.visit_time DESC LIMIT ? OFFSET ?';
    const query_params = [...params, parseInt(limit), parseInt(offset)];
    
    // Get total count
    db.get(countSql, params, (err, countRow) => {
      if (err) {
        console.error('Error counting visits:', err);
        return res.status(500).json({ 
          success: false, 
          message: 'Internal server error' 
        });
      }
      
      const total = countRow.count;
      
      // Get the actual data
      db.all(sql, query_params, (err, rows) => {
        if (err) {
          console.error('Error fetching visits:', err);
          return res.status(500).json({ 
            success: false, 
            message: 'Internal server error' 
          });
        }
        
        res.json({ 
          success: true, 
          data: rows,
          limit: parseInt(limit),
          offset: parseInt(offset),
          total: total
        });
      });
    });
  } catch (error) {
    console.error('Unexpected error:', error);
    res.status(500).json({ 
      success: false, 
      message: 'Internal server error' 
    });
  }
});

/**
 * Delete visits based on criteria
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
router.delete('/', (req, res) => {
  try {
    const { ids, olderThan } = req.body;
    
    if (!ids && !olderThan) {
      return res.status(400).json({ 
        success: false, 
        message: 'Either ids or olderThan must be provided' 
      });
    }
    
    if (ids && Array.isArray(ids) && ids.length > 0) {
      // Delete specific visits by IDs
      const placeholders = ids.map(() => '?').join(',');
      const sql = `DELETE FROM visits WHERE id IN (${placeholders})`;
      
      db.run(sql, ids, function(err) {
        if (err) {
          console.error('Error deleting visits:', err);
          return res.status(500).json({ 
            success: false, 
            message: 'Internal server error' 
          });
        }
        
        res.json({ 
          success: true, 
          message: `Deleted ${this.changes} visit(s)`,
          deletedCount: this.changes
        });
      });
    } else if (olderThan) {
      // Delete visits older than a specific date
      const sql = `DELETE FROM visits WHERE visit_time < ?`;
      
      db.run(sql, [olderThan], function(err) {
        if (err) {
          console.error('Error deleting visits:', err);
          return res.status(500).json({ 
            success: false, 
            message: 'Internal server error' 
          });
        }
        
        res.json({ 
          success: true, 
          message: `Deleted ${this.changes} visit(s)`,
          deletedCount: this.changes
        });
      });
    } else {
      return res.status(400).json({ 
        success: false, 
        message: 'Invalid request parameters' 
      });
    }
  } catch (error) {
    console.error('Unexpected error:', error);
    res.status(500).json({ 
      success: false, 
      message: 'Internal server error' 
    });
  }
});

module.exports = router;